package com.wenbing.miio.core;

import java.net.SocketAddress;

/**
 * @author wen bing
 * @projectName: miio
 * @package: core.ps
 * @className: SContext
 * @date 2024/09/19 12:31
 **/
public class MapNetworkLayerContext extends MapContext implements NetworkLayerContext {

    private NetworkLayerContext parent;

    private Context shareContext;

    public MapNetworkLayerContext(NetworkLayerContext parent, Context shareContext) {
        super();
        assert shareContext != null;
        this.parent = parent;
        this.shareContext = shareContext;
    }

    @Override
    public NetworkLayerContext getParentContext() {
        return parent;
    }

    @Override
    public void setShareAttribute(String key, Object attr) {
        shareContext.setAttribute(key, attr);
    }

    @Override
    public Context getShareContext() {
        return shareContext;
    }

    public static NetworkLayerContext newContext(NetworkLayerContext parent, SocketAddress localAddress, SocketAddress remoteAddress) {
        Context shareContext = parent == null ? new MapContext() : parent.getShareContext();
        NetworkLayerContext context = new MapNetworkLayerContext(parent, shareContext);
        context.setShareAttribute(NetworkLayerContext.LOCAL_ADDRESS, localAddress);
        context.setShareAttribute(NetworkLayerContext.REMOTE_ADDRESS, remoteAddress);
        return context;
    }

    public static NetworkLayerContext rootContext(SocketAddress localAddress, SocketAddress remoteAddress) {
        return newContext(null, localAddress, remoteAddress);
    }
}
